package playtools.wizard;

import java.io.File;

import org.apache.commons.lang.StringUtils;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.dialogs.WorkingSetGroup;

import playtools.PlayTools;
import playtools.util.DialogUtil;
import playtools.util.LayoutUtil;
import playtools.util.UIUtils;

public class NewProjectPage extends WizardPage implements ModifyListener{
	private Text nameText;
	private Text locationText;
	private Composite dirComp;
	private Text appNameText;
	private Button defaultAppNameBtn;
	private Button defaultLocationBtn;
	private WorkingSetGroup workingSetGroup;
	
	protected NewProjectPage() {
		super("Create Play Project");
	}

	public void createControl(Composite parent) {
		Composite comp = new Composite(parent, SWT.None);
		LayoutUtil.gdb(comp, 1, 1);
		LayoutUtil.gl(comp, 1, 13, 7);
		
		Composite nameComp = new Composite(comp, SWT.None);
		LayoutUtil.gdh(nameComp);
		LayoutUtil.gl(nameComp, 2);
		new Label(nameComp, SWT.None).setText("Project name: ");
		nameText = new Text(nameComp, SWT.BORDER);
		LayoutUtil.gdh(nameText);
		
		Composite locationComp = new Composite(comp, SWT.None);
		LayoutUtil.gdh(locationComp);
		LayoutUtil.gl(locationComp, 1, 3, 3, 2, 0);
		
		defaultLocationBtn = new Button(locationComp, SWT.CHECK);
		defaultLocationBtn.setText("use default location");
		defaultLocationBtn.addSelectionListener(new SelectionListener(){
			public void widgetDefaultSelected(SelectionEvent e) {}
			public void widgetSelected(SelectionEvent e) {
				setLocationDefault(defaultLocationBtn.getSelection());
			}
		});
		dirComp = new Composite(locationComp, SWT.None);
		LayoutUtil.gdh(dirComp);
		LayoutUtil.gl(dirComp, 3);
		new Label(dirComp, SWT.None).setText("Location: ");
		locationText = new Text(dirComp, SWT.BORDER);
		LayoutUtil.gdh(locationText);
		Button selDirBtn = new Button(dirComp, SWT.None);
		selDirBtn.setText("Browse...");
		selDirBtn.addSelectionListener(new SelectionListener(){
			public void widgetDefaultSelected(SelectionEvent e) {}
			public void widgetSelected(SelectionEvent e) {
				String dir = DialogUtil.openFolderDialog("选择目录", "选择Play项目所在目录");
			    if(!StringUtils.isEmpty(dir)){
			    	locationText.setText(dir);
			    }
			}
		});
		
		Group appNameComp = new Group(comp, SWT.None);
		appNameComp.setText("Customs");
		LayoutUtil.gdh(appNameComp);
		LayoutUtil.gl(appNameComp, 2, 8, 8);
		defaultAppNameBtn = new Button(appNameComp, SWT.CHECK);
		defaultAppNameBtn.setText("use project name as app name ");
		appNameText = new Text(appNameComp, SWT.BORDER);
		LayoutUtil.gdh(appNameText);
		defaultAppNameBtn.addSelectionListener(new SelectionListener(){
			public void widgetDefaultSelected(SelectionEvent e) {}
			public void widgetSelected(SelectionEvent e) {
				setAppNameDefault(defaultAppNameBtn.getSelection());
			}
		});
		
		createWorkingSetGroup(comp);
		this.nameText.addModifyListener(this);
		this.locationText.addModifyListener(this);
		this.appNameText.addModifyListener(this);
		this.setControl(comp);
		
		this.setTitle("Create Play Project");
		initValues();
		doVerifyContents();
	}
	
	public void createWorkingSetGroup(Composite composite) {
		/* Resource working set ID */
		final String RESOURCE= "org.eclipse.ui.resourceWorkingSetPage"; //$NON-NLS-1$
		/** Java working set ID */
		final String JAVA= "org.eclipse.jdt.ui.JavaWorkingSetPage"; //$NON-NLS-1$

		/** 'Other Projects' working set ID */
		final String OTHERS= "org.eclipse.jdt.internal.ui.OthersWorkingSet";
		workingSetGroup = new WorkingSetGroup(composite, 
				(IStructuredSelection) UIUtils.getGlobalWindow().
				getSelectionService().getSelection(),
				new String[] {RESOURCE, JAVA, OTHERS});
	}
	
	public IWorkingSet[] getSelectedWorkingSets(){
		return this.workingSetGroup.getSelectedWorkingSets();
	}
	
	private void initValues() {
		this.defaultAppNameBtn.setSelection(true);
		this.defaultLocationBtn.setSelection(true);
		setLocationDefault(true);
		setAppNameDefault(true);
	}

	private void doVerifyContents(){
		String result = this.verify();
		if(result == null){
			this.setMessage("fill play configurations", INFORMATION);
			this.setPageComplete(true);
		}else{
			this.setMessage(result, ERROR);
			this.setPageComplete(false);
		}
	}
	
	public String verify(){
		String chkInfo = PlayTools.checkPlayPath();
		if(chkInfo != null){
			return chkInfo;
		}
		String projName = this.nameText.getText();
		IStatus status = getWorkspace().validateName(projName, IResource.PROJECT);
	    if(!status.isOK()){
	    	return "project name invalid: " + status.getMessage();
	    }
	    IProject handle = getWorkspace().getRoot().getProject(projName);
	    if(handle.exists()){
	    	return "project '" + projName + "'name is already exist in workspace";
	    }
	    String location = this.locationText.getText();
	    if(!new File(location).isDirectory()){
	    	return "location isn't a exist directory";
	    }
	    String fullPath = location + File.separator + projName;
	    if(new File(fullPath).exists()){
	    	return "the file '" + fullPath + "' is already exist";
	    }
	    if(!this.defaultAppNameBtn.getSelection()){
	    	String appName = this.appNameText.getText();
	    	status = getWorkspace().validateName(appName, IResource.FILE);
	        if(!status.isOK()){
	        	return "app name invalid: " + status.getMessage();
	        }
	    }
	    return null;
	}
	
	public void setValues(PlayProjectConfiguration configuration){
		configuration.setPlayCmd(PlayTools.getPlayPath());
		configuration.setProjectName(this.nameText.getText().trim());
		if(this.defaultAppNameBtn.getSelection()){
			configuration.setAppName(this.nameText.getText().trim());
		}else{
			configuration.setAppName(this.appNameText.getText().trim());
		}
		configuration.setLocation(this.locationText.getText().trim());
		
	}
	
	private String getDefaultRoot(){
		return getWorkspace().getRoot().getLocation().toFile().getAbsolutePath();
	}
	
	private IWorkspace getWorkspace(){
		return ResourcesPlugin.getWorkspace();
	}
	
	private void setLocationDefault(boolean isDefault){
		this.dirComp.setEnabled(!isDefault);
		for(Control cs: this.dirComp.getChildren()){
			cs.setEnabled(!isDefault);
		}
		if(isDefault){
			this.locationText.setText(getDefaultRoot());
		}
		this.doVerifyContents();
	}
	
	private void setAppNameDefault(boolean isDefault){
		this.appNameText.setEnabled(!isDefault);
		this.doVerifyContents();
	}

	public void modifyText(ModifyEvent e) {
		doVerifyContents();
	}

}
